import React, { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { message, Modal, Button } from 'antd';
import {HomeOutlined,
  ReadOutlined,
  VideoCameraOutlined,
  RobotOutlined,
  BookOutlined,
  MessageOutlined,
  HeartOutlined,
  ProfileOutlined,
  UserOutlined
} from '@ant-design/icons';
import styles from './Book.module.css';
import axios from 'axios';

export default function Book() {
  const navigate = useNavigate();
  const [books, setBooks] = useState([]);
  const [activeCategory, setActiveCategory] = useState('all');
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [activeTab, setActiveTab] = useState('/books');
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });
  const [purchaseModalVisible, setPurchaseModalVisible] = useState(false);
  const [selectedBook, setSelectedBook] = useState(null);
  const [purchaseLoading, setPurchaseLoading] = useState(false);
  const menuRef = useRef(null);

  // 统一的退出登录处理函数
  const handleLogout = () => {
    // 清除本地存储的用户信息
    localStorage.removeItem('currentUser');
    localStorage.removeItem('token');
    
    message.success('已成功退出登录');
    
    // 延迟跳转到登录页面
    setTimeout(() => {
      navigate('/login');
    }, 1000);
  };

  // 处理购买按钮点击
  const handleBuyClick = (book) => {
    // 检查用户是否登录
    const currentUser = localStorage.getItem('currentUser');
    const token = localStorage.getItem('token');
    
    if (!currentUser || !token) {
      message.error('请先登录');
      navigate('/login');
      return;
    }
    
    setSelectedBook(book);
    setPurchaseModalVisible(true);
  };

  // 处理支付宝购买
  const handlePurchase = async () => {
    if (!selectedBook) return;
    
    setPurchaseLoading(true);
    try {
      // 获取用户信息
      const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
      const token = localStorage.getItem('token');
      
      if (!token) {
        message.error('请先登录');
        return;
      }

      // 创建订单
      const orderResponse = await axios.post('http://localhost:3001/api/create-book-order', {
        bookId: selectedBook.id,
        bookTitle: selectedBook.title,
        price: selectedBook.price,
        userNickname: currentUser.nickname || currentUser.username || '用户',
        phone: currentUser.phone || '13800000000'
      }, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!orderResponse.data.success) {
        throw new Error(orderResponse.data.message || '创建订单失败');
      }

      // 发起支付宝支付
      const paymentResponse = await axios.post('http://localhost:3001/api/alipay', {
        outTradeNo: orderResponse.data.data.orderId,
        subject: `购买《${selectedBook.title}》`,
        totalAmount: parseFloat(selectedBook.price.replace('¥', ''))
      });

      //创建支付表单并提交
      // const form = document.createElement('form');
      // form.method = 'POST';
      // form.action = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do';
      // form.innerHTML = paymentResponse.data;
      // document.body.appendChild(form);
      // form.submit();
      // document.body.removeChild(form);

      const div = document.createElement('div');
      div.innerHTML = paymentResponse.data;
      document.body.appendChild(div);
      document.forms[0].submit();


      // 关闭模态框
      setPurchaseModalVisible(false);
      setSelectedBook(null);
      
      message.success('正在跳转到支付宝支付页面...');
      
    } catch (error) {
      console.error('购买失败:', error);
      message.error(error.response?.data?.message || '购买失败，请稍后重试');
    } finally {
      setPurchaseLoading(false);
    }
  };

  // 取消购买
  const handleCancelPurchase = () => {
    setPurchaseModalVisible(false);
    setSelectedBook(null);
  };

  // 添加响应式断点
  const isMobile = windowSize.width < 768;
  const isTablet = windowSize.width >= 768 && windowSize.width <= 1024;
  const isDesktop = windowSize.width > 1024;

  // 添加窗口大小变化监听
  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsMenuOpen(false);
      }
    };

    if (isMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isMenuOpen]);

  // 移除重复声明，使用已有的 state

  // 图书分类
  const categories = [
    { id: 'all', name: '全部图书' },
    { id: 'math', name: '数学思维' },
    { id: 'chinese', name: '语文阅读' },
    { id: 'english', name: '英语学习' },
    { id: 'science', name: '科学探索' },
    { id: 'art', name: '艺术创作' }
  ];

  // 图书数据
  const booksData = [
    {
      id: 1,
      title: "摩比爱数学",
      description: "畅销超400万册的思维启蒙网红图书，培养孩子的数学思维",
      category: "math",
      author: "学而思教研团队",
      publisher: "学而思出版社",
      price: "¥135",
      originalPrice: "¥168",
      image: "/image/2.webp",
      tag: "热销",
      rating: 4.8,
      sales: "400万+"
    },
    {
      id: 2,
      title: "学而思秘籍",
      description: "思维培养、基础巩固，全面提升学习能力",
      category: "math",
      author: "学而思教研团队",
      publisher: "学而思出版社",
      price: "¥41.7",
      originalPrice: "¥59",
      image: "/image/1.webp",
      tag: "推荐",
      rating: 4.6,
      sales: "200万+"
    },
    {
      id: 3,
      title: "摩比启蒙机",
      description: "启蒙新方式一机全搞定，智能学习好帮手",
      category: "science",
      author: "摩比团队",
      publisher: "摩比出版社",
      price: "¥79",
      originalPrice: "¥99",
      image: "/image/3.png",
      tag: "新品",
      rating: 4.7,
      sales: "50万+"
    },
    {
      id: 4,
      title: "学而思基本功",
      description: "扩展延伸、阶段复习，夯实学习基础",
      category: "chinese",
      author: "学而思教研团队",
      publisher: "学而思出版社",
      price: "¥58.3",
      originalPrice: "¥78",
      image: "https://img.alicdn.com/i1/421334959/O1CN01cgAtkq1mVGot4F9wK_!!421334959.jpg",
      tag: "限时",
      rating: 4.5,
      sales: "150万+"
    },
    {
      id: 5,
      title: "课内培优",
      description: "思维培养、基础巩固，课内课外双提升",
      category: "math",
      author: "学而思教研团队",
      publisher: "学而思出版社",
      price: "¥43",
      originalPrice: "¥58",
      image: "https://tse2-mm.cn.bing.net/th/id/OIP-C.jaN0XcPm-KwxURNlAzoMFAHaHa?w=201&h=201&c=7&r=0&o=5&dpr=1.5&pid=1.7",
      rating: 4.4,
      sales: "120万+"
    },
    {
      id: 6,
      title: "英语启蒙绘本",
      description: "趣味英语学习，通过绘本培养语言能力",
      category: "english",
      author: "英语教研团队",
      publisher: "教育出版社",
      price: "¥89",
      originalPrice: "¥128",
      image: "https://tse2-mm.cn.bing.net/th/id/OIP-C.HT3z6I1kMkVvLLEJyXFTFAHaHa?w=190&h=190&c=7&r=0&o=5&dpr=1.5&pid=1.7",
      tag: "热销",
      rating: 4.9,
      sales: "80万+"
    }
  ];

  // 根据分类筛选图书
  const filteredBooks = activeCategory === 'all' 
    ? booksData 
    : booksData.filter(book => book.category === activeCategory);

  const tabItems = [
    { icon: <HomeOutlined />, label: "首页", path: "/" },
    { icon: <ProfileOutlined />, label: "课程", path: "/coursess" },
    { icon: <ReadOutlined />, label: "图书", path: "/books" },
    { icon: <MessageOutlined />, label: "聊天", path: "/c" },
    { icon: <UserOutlined />, label: "我的", path: "/d" }
  ];

  // 根据当前路径设置active tab
  useEffect(() => {
    const currentPath = window.location.pathname;
    setActiveTab(currentPath);
  }, []);

  return (
    <div className={styles['book-container']}>
      {/* Header Navigation Bar - 与Home.jsx相同的导航栏 */}
      <header className={styles['header']}>
        <div className={styles['header-content']}>
          {/* Logo */}
          <div className={styles['logo']}>
            <div className={styles['logo-icon']}>
              <div className={`${styles['logo-square']} ${styles['red']}`}></div>
              <div className={`${styles['logo-square']} ${styles['green']}`}></div>
              <div className={`${styles['logo-square']} ${styles['blue']}`}></div>
              <div className={`${styles['logo-square']} ${styles['yellow']}`}></div>
            </div>
            <span className={styles['logo-text']}>智绘师</span>
          </div>

          {/* Navigation Links */}
          <nav className={styles['nav-links']}>
            <a className={styles['nav-link']} onClick={() => navigate('/')}>
              首页
            </a>
            <a className={styles['nav-link']}>
              学习机
            </a>
            <a className={styles['nav-link']}>
              智绘师网校
            </a>
            <a className={styles['nav-link']} onClick={() => navigate('/coursess')}>
              培优素养课
            </a>
            <a className={`${styles['nav-link']} ${styles['active']}`}>
              智能图书
            </a>
            <a className={styles['nav-link']}>
              九章大模型
            </a>
            <a className={styles['nav-link']}>
              我们的故事
            </a>
          </nav>

          {/* Right Side Menu */}
          <div className={styles['menu-toggle']} onClick={toggleMenu} ref={menuRef}>
            <div className={styles['hamburger']}>
              <span></span>
              <span></span>
              <span></span>
            </div>
            <span className={styles['menu-text']}>全部</span>
            
            {/* 抽屉菜单 */}
            {isMenuOpen && (
              <div className={styles['drawer-overlay']} onClick={toggleMenu}>
                <div 
                  className={`${
                    isMobile ? styles['mobile-drawer'] : 
                    isTablet ? styles['tablet-drawer'] : 
                    styles['desktop-drawer']
                  }`} 
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className={styles['drawer-header']}>
                    <span className={styles['drawer-title']}>智绘师</span>
                    <button className={styles['drawer-close']} onClick={toggleMenu}>×</button>
                  </div>
                  
                  <div className={styles['drawer-content']}>
                    <div className={styles['menu-section']}>
                      <div className={styles['menu-item']}>选课</div>
                      <div className={styles['menu-item']}>学习俱乐部</div>
                      <div className={styles['menu-item']}>课程表</div>
                      <div className={styles['menu-item']}>智绘师移动应用</div>
                      <div className={styles['menu-item']} onClick={() => navigate('/books')}>智能图书</div>
                      <div className={styles['menu-item']} onClick={() => navigate('/coursess')}>精品课臻选</div>
                      <div className={styles['menu-item']}>精品课讲堂</div>
                      <div className={styles['menu-item']}>上海智绘课堂</div>
                    </div>
                    
                    <div className={styles['menu-divider']}></div>
                    
                    <div className={styles['menu-section']}>
                      <div className={styles['menu-item']}>关于智绘师</div>
                      <div className={styles['menu-item']}>帮助中心</div>
                    </div>
                    
                    <div className={styles['drawer-footer']}> 
                      <button 
                        className={styles['register-btn']}
                        onClick={handleLogout}
                      >
                        <span className={styles['btn-text']}>退出登录</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* 页面主要内容 */}
      <main className={styles['main-content']} style={{ 
        paddingBottom: isMobile ? '80px' : '40px' 
      }}>
        <div className={styles['content-wrapper']}>
          {/* 页面标题 */}
          <div className={styles['page-header']}>
            <h1 className={styles['page-title']}>智能图书</h1>
            <p className={styles['page-subtitle']}>为孩子的成长提供优质的图书资源</p>
            <button 
              className={styles['history-btn']}
              onClick={() => navigate('/purchase-history')}
            >
              查看购买历史
            </button>
          </div>

          {/* 图书分类 */}
          <div className={styles['book-categories']}>
            {categories.map(category => (
              <button
                key={category.id}
                className={`${styles['category-btn']} ${
                  activeCategory === category.id ? styles['active'] : ''
                }`}
                onClick={() => setActiveCategory(category.id)}
              >
                {category.name}
              </button>
            ))}
          </div>

          {/* 图书网格 */}
          <div className={styles['book-grid']}>
            {filteredBooks.map(book => (
              <div key={book.id} className={styles['book-item']}>
                {book.tag && <span className={styles['book-tag']}>{book.tag}</span>}
                <div className={styles['book-image']}>
                  <img src={book.image} alt={book.title} />
                </div>
                <div className={styles['book-info']}>
                  <h3 className={styles['book-title']}>{book.title}</h3>
                  <p className={styles['book-description']}>{book.description}</p>
                  <div className={styles['book-meta']}>
                    <span className={styles['book-author']}>{book.author}</span>
                    <span className={styles['book-publisher']}>{book.publisher}</span>
                  </div>
                  <div className={styles['book-rating']}>
                    <span className={styles['rating-stars']}>
                      {'★'.repeat(Math.floor(book.rating))}
                      {'☆'.repeat(5 - Math.floor(book.rating))}
                    </span>
                    <span className={styles['rating-score']}>{book.rating}</span>
                    <span className={styles['book-sales']}>{book.sales}</span>
                  </div>
                  <div className={styles['book-footer']}>
                    <div className={styles['book-price']}>
                      <span className={styles['current-price']}>{book.price}</span>
                      {book.originalPrice && (
                        <span className={styles['original-price']}>{book.originalPrice}</span>
                      )}
                    </div>
                    <button 
                      className={styles['buy-btn']}
                      onClick={() => handleBuyClick(book)}
                    >
                      立即购买
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </main>

      {/* 移动端底部导航 */}
      {isMobile && (
        <div className={styles['tab-bar']}>
          {tabItems.map((item) => (
            <div 
              key={item.path} 
              className={`${styles['tab-item']} ${activeTab === item.path ? styles['active'] : ''}`}
              onClick={() => {
                setActiveTab(item.path);
                navigate(item.path);
              }}
            >
              <span className={styles['tab-icon']}>{item.icon}</span>
              <span className={styles['tab-label']}>{item.label}</span>
            </div>
          ))}
        </div>
      )}
      
      {/* 购买确认模态框 */}
      <Modal
        title="确认购买"
        open={purchaseModalVisible}
        onOk={handlePurchase}
        onCancel={handleCancelPurchase}
        confirmLoading={purchaseLoading}
        okText="确认购买"
        cancelText="取消"
        width={500}
      >
        {selectedBook && (
          <div className={styles['purchase-modal-content']}>
            <div className={styles['book-preview']}>
              <img src={selectedBook.image} alt={selectedBook.title} />
              <div className={styles['book-info']}>
                <h3>{selectedBook.title}</h3>
                <p>{selectedBook.description}</p>
                <div className={styles['price-info']}>
                  <span className={styles['current-price']}>{selectedBook.price}</span>
                  {selectedBook.originalPrice && (
                    <span className={styles['original-price']}>{selectedBook.originalPrice}</span>
                  )}
                </div>
              </div>
            </div>
            <div className={styles['purchase-notice']}>
              <h4>购买须知：</h4>
              <ul>
                <li>购买后图书将立即添加到您的账户</li>
                <li>支持在线阅读和下载</li>
                <li>购买后不支持退款</li>
                <li>如有问题请联系客服</li>
              </ul>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
